<?php
namespace app\yxwadmin\controller;
use think\Controller;
use think\Session;

/**
* 后台登录模块
*/
class Login extends Controller{

    public function index(){
        //$sysset = model('SetModel')->find();
        $data['sysname'] = "美文音乐相册";//$sysset['sysname'];
        $data['copyright'] = "";//$sysset['copyright'];

        $this->assign('data', $data);
        return $this->view->fetch('index/login');
    }

    public function checklogin(){
        $now=time();
        $uname=input('post.user_name','');
        $pwd=input('post.pass_word','','md5');
        if(empty($uname)){
            $this->error('用户登录名不能为空',url('login/index'));
        }
        $ip=get_client_ip();
        $area= "暂时停止"; //get_ip_data($ip);
        
        //验证访客信息
        $this->check_visitor($ip,$area);

        $usersModel=model('UserModel');
        $where['user_name']=$uname;        
        $res=$usersModel->where($where)->field('id,user_name,pass_word,status,last_login_ip,last_location,last_login_time,fail_count,limit_end')->find();
        if($res['status']==1){
            $this->error('该用户已被冻结请联系管理员',url('login/index'));            
        }
        else if($res&&($pwd===$res['pass_word'])){
            //如果输入密码错误次数过多导致锁定账号
            if ($res['limit_end'] > $now) {
                $minute = $minute = ceil(($res['limit_end']-$now)/60);
                $this->error('密码错误次数过多，请于：'.$minute.'分钟后再尝试',url('login/index'));
            }

            session('uid',$res['id']);
            session('uname',$res['user_name']);
            session('last_login_info',array(
                'last_login_ip'=>$res['last_login_ip'],
                'last_location'=>$res['last_location'],
                'last_login_time'=>$res['last_login_time'],
            ));
            
            $upret = $usersModel->where(array('id'=>$res['id']))->update(array(
                    'last_login_time'=>$now,
                    'update_time'=>$now,
                    'last_login_ip'=>$ip,
                    'last_location'=>$area,
                    'fail_count'=>0,
                    'limit_end'=>0
                )
            );
            //记录登录日志
            //if ($this->login_log($now,$ip,$area,$res['user_name'])) {
            //$this->success('登录成功', url('index/index'),"",1);
            if($upret){
                $url = get_host().url('index/index');
                header("Location: $url");
                exit();
            }else {
                 $this->error('登录失败',url('login/index'));
            }
        }else{
            if ($res&&($pwd!==$res['pass_word'])) {
                //如果输入密码错误时间过期则重置密码错误次数
                if ($res['limit_end'] > 0) {
                    if ($res['limit_end'] < $now) {
                        $res['fail_count'] = 0;
                        $res['limit_end'] = 0;
                    }else {
                        $minute = ceil(($res['limit_end']-$now)/60);
                        $this->error('密码错误次数过多，请于：'.$minute.'分钟后再尝试',url('login/index'));
                    }
                }
                //如果密码错误次数超过限制就锁定账号
                $limit_err = 5; //限制输入密码最大错误次数
                if ($res['fail_count'] == ($limit_err-1)) {
                    $usersModel->where(array('id'=>$res['id']))->update(array(
                            'limit_end' => $now + 1800
                        )
                    );
                }elseif ($res['fail_count'] < ($limit_err-1)) {
                    $usersModel->where(array('id'=>$res['id']))->update(array(
                            'fail_count' => $res['fail_count'] + 1,
                            'limit_end'=> $res['limit_end']
                        )
                    );
                }
            }
            $this->error('用户登录名密码不正确',url('login/index'));
        }
    }

    public function logout(){
        session('uid', null);
        session('uname', null);
        if(session('?'.config('USER_AUTH_KEY'))) {
            session(config('USER_AUTH_KEY'),null);        
            redirect(config('login/index'));
        }else {
            $url = get_host().url('login/index');
            header("Location: $url");
            exit();
        }
    }

    /**
     * 验证访客信息
     */
    private function check_visitor($ip,$area){
        if ($ip == '0.0.0.0') {
            return true;
        }
        //验证是否是黑名单
        $visitor;
        $where = ['ip'=>$ip];
        if (cookie('visitor')) {
            $visitor = cookie('visitor');
            if ($visitor['state'] == 1) {
                $this->error('你是黑名单用户!',url('login/index'));
            }

            $max_c1 = 4; //10秒内最多访问 $max_c1 次，超过次数则提示操作频繁
            $max_c2 = 5; //10秒内访问超过 $max_c2 次就拉黑
            if ($visitor['count'] > ($max_c1-1)) {
                if ($visitor['count'] > ($max_c2-1)) {
                    model('VisitorModel')->where($where)->update(['state'=>1]);
                    $visitor['state'] = 1;
                    cookie('visitor', $visitor, 60*60*24*365);
                    $this->error('你已被拉入黑名单!',url('login/index'));
                }

                $visitor['count'] += 1;
                cookie('visitor', $visitor, 10);
                $this->error('操作过于频繁!',url('login/index')); 
            }else {
                $visitor['count'] += 1;
                cookie('visitor', $visitor, 10);
            }
        }else {
            $visitor['ip'] = $ip;
            $visitor['count'] = 1;
            $visitor['state'] = 0;
            $visitor['update_time'] = time();
            cookie('visitor', $visitor, 10);
        }

        $info = model('VisitorModel')->where($where)->find();
        if ($info) {
            if ($info['state'] == 1) {
                $visitor['state'] = 1;
                cookie('visitor', $visitor, 60*60*24*365);
                $this->error('你是黑名单用户!',url('login/index'));
            }else {
                $area = $info['area'];
                $data = array(
                    'count' => $info['count'] + 1,
                    'update_time' => time(),
                );
                model('VisitorModel')->where($where)->update($data);
            }
        }else {
            $data = array(
                'ip' => $ip,
                'area' => $area,
                'update_time' => time(),
            );
            model('VisitorModel')->insert($data);
        }

    }

    /**
     * 记录登录日志
     * @param int    $now       当前时间戳
     * @param string $ip        访客IP
     * @param string $area      访客省份及城市
     * @param string $user_name 登录名
     */
    private function login_log($now,$ip,$area,$user_name){
        if ($ip == '0.0.0.0') {
            return true;
        }
        $today = date('Y-m-d',$now);
        $logFolder = ROOT_PATH.'runtime/log/login';
        $logFile = $logFolder.'/'.$today.'.log';
        $log = '【'.date('Y-m-d H:i:s',$now).'】【'.$ip.'】【'.$area.'】【'.$user_name.'】';
        if (!is_dir($logFolder)) {
            mkdir($logFolder);
        }
        //如果日志超过10天则删除
        $old_log = array();
        foreach (scandir($logFolder.'/') as $file) {
            if ($file != '.' && $file != '..') {
                $fileTime = strtotime(strstr($file, '.', true).' 00:00:00');
                if (($fileTime+864000) < $now) {
                    unlink($logFolder.'/'.$file);
                }
            }
        }
        return file_put_contents($logFile, $log."\r\n", FILE_APPEND|LOCK_EX);
    }


}